package com.codejoys.ssm.service.Impl;

import com.codejoys.ssm.dao.SchoolDao;
import com.codejoys.ssm.domain.School;
import com.codejoys.ssm.domain.SchoolExample;
import com.codejoys.ssm.dto.PageData;
import com.codejoys.ssm.mapper.SchoolMapper;
import com.codejoys.ssm.service.SchoolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service

public class SchoolServiceImpl implements SchoolService {

    @Autowired
    SchoolMapper schoolMapper;

    @Autowired
    SchoolDao schoolDao;
    public Integer insert(School school){

      // return schoolMapper.insert(school);
        schoolMapper.insert(school);
        return school.getId();


    }

    @Override
    public void deleteById(Integer[] ids) {
        //能用一条sql语句就不要用多条
        //尽量避免再循环里执行sql语句
//        for (Integer id:ids){
//            schoolMapper.deleteByPrimaryKey(id);
//        }
        schoolDao.deleteByIds(ids);
    }

    @Override
    public void deleteById(Integer id) {
        schoolDao.deleteById(id);
    }

    @Override
    public PageData<School> findPage(Integer page, Integer limit) {
        //第一步，查总计录数

        final long count = schoolMapper.countByExample(null);

        //第二步，查当前页数据
        //0-》1  10-》2
        final List<School> data = schoolDao.findPage((page-1) * limit, limit);

        return new PageData<>(count,data);
    }

    @Override
    public School findById(Integer id) {
        return schoolMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<School> findByCondition(School school) {
        //根据名字查
//        if(school.getName()!=null&&school.getName().length()==0){
//
//        }
        SchoolExample example=new SchoolExample();
        //select * from school where name like '%工程大%'
        //example.createCriteria().andNameLike("%工程大%");
       final  SchoolExample.Criteria criteria = example.createCriteria();
        if(!StringUtils.isEmpty(school.getName())){
            criteria.andNameLike("%"+school.getName()+"%");

            }
            if (!StringUtils.isEmpty(school.getProvince())){
               criteria.andProvinceLike("%"+school.getProvince()+"%");
            }
            //where is_985==true
        if (school.getIs985()!=null){
            criteria.andIs985EqualTo(true);

        }
        return schoolMapper.selectByExample(example);
    }


}
